from mitmproxy import ctx,http
# http://mitm.it/ 证书
# mitmdump.exe -s .\xiaoyuan.py
# mitmweb
import re
import requests

def setM3u8Status():
    """1 表示下载好了 """
    with open("m3u8Status.txt", "w") as f:
        f.write("0")


def response(flow):
    titlesearch = re.search(r"roomId=(.*?)&liveUuid=(.*)", flow.request.url)
    if titlesearch:
        global roomIdAndUid
        roomIdAndUid = titlesearch
        centent = flow.response.get_content().decode('utf-8')
        titleRe = re.search(r'<meta property="og:title" content="(.*?)">',centent)
        global title
        title = titleRe.group(1)
        print(title)
    else:
        m3u8math = re.match(r"^(.*)/(.*?)_normal.m3u8", flow.request.url)
        if m3u8math:
            print("===============这是m3u8格式的文件响应============================")
            print("房间号：", roomIdAndUid.group(2), "========", roomIdAndUid.group(1))
            centen = flow.response.get_text()
            try:
                with open(r"./m3u8/{0}.m3u8".format(title.replace("/", "-")).replace("\t", " "), "w") as f:
                    f.write(centen)
                setM3u8Status()
            except OSError as e:
                print("==================================错误====================================")
                print(e)
                print("==================================错误====================================")
                with open("./log.txt".format(title), "a") as f:
                    f.write("标题: {0}, roomId:{1}, UuId: {2}, url:https://n.dingtalk.com/dingding/live-room/index.html?roomId={3}&liveUuid={4}\n".
                                                                            format(title,
                                                                                roomIdAndUid.group(1),
                                                                                 roomIdAndUid.group(2),
                                                                                 roomIdAndUid.group(1),
                                                                                 roomIdAndUid.group(2),
                                                                                 ))
            print("===============结束============================")
